package com.imay.live.view.viewpager;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.imay.live.view.custom.RoomBaseView;

import java.lang.ref.WeakReference;

/**
 * Created by jeaman on 2017/4/7.
 */

public class CViewPager extends VerticalViewPager {
    private WeakReference<View> mInterceptView;
    private boolean canScroll = true;
    private boolean canTouch = true;
    private OnTouchListener mTouchListener;
    private RoomBaseView mDispatchTouchViewGroup;   //触摸事件分发给其他

    public CViewPager(Context context) {
        super(context);
    }

    public CViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setInterceptView(View view) {
        mInterceptView = new WeakReference<View>(view);
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
        //子view为ScrollingView时，滑动到两端时不出发viewpager滑动
        return super.canScroll(v, checkV, dx, x, y) || (v == mInterceptView.get());
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (canTouch) {
            if (mTouchListener != null) {
                mTouchListener.onTouch(this, ev);
            }
        }
        if (mDispatchTouchViewGroup != null) {
            mDispatchTouchViewGroup.dispatchTouchEvent(ev);
            //滑动聊天列表时禁止滑动viewpager
            if (mDispatchTouchViewGroup.isInterceptTouchEvent(ev)) {
                return false;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (canScroll || mIsBeingDragged) { //正在滑动，需要等待结束才禁止事件
            try {
                return super.onInterceptTouchEvent(ev);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (canScroll || mIsBeingDragged) { //正在滑动，需要等待结束才禁止事件
            return super.onTouchEvent(event);
        }
        return false;
    }

    @Override
    public void setOnTouchListener(OnTouchListener listener) {
        mTouchListener = listener;
    }

    public void toggleLock() {
        canScroll = !canScroll;
    }

    public void setCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
    }

    public boolean isCanScroll() {
        return canScroll;
    }

    public void setCanTouch(boolean canTouch) {
        this.canTouch = canTouch;
    }

    public void setDispatchTouchViewGroup(RoomBaseView dispatchTouchViewGroup) {
        mDispatchTouchViewGroup = dispatchTouchViewGroup;
    }
}
